package model

import (
	"errors"
	"github.com/hwcer/cosgo/schema"
	"github.com/hwcer/updater"
	"github.com/hwcer/updater/dataset"
	"github.com/hwcer/updater/operator"
	"server/share/config"
)

func init() {
	Register(&Record{})
}

type Record struct {
	OID   string `bson:"_id" json:"oid" `
	Uid   string `bson:"uid" json:"-"  index:"name:_idx_uid_primary" `
	IID   int32  `bson:"iid" json:"iid"`
	Value int64  `bson:"val" json:"val"`
}

func (this *Record) Get(k string) (any, bool) {
	switch k {
	case "oid", "_id", "OID":
		return this.OID, true
	case "iid", "IID":
		return this.IID, true
	case "val", "Value":
		return this.Value, true
	}
	return nil, false
}

func (this *Record) Set(k string, v any) (any, bool) {
	switch k {
	case "val", "Value":
		this.Value = dataset.ParseInt64(v)
		return this.Value, true
	}
	return nil, true
}

func (this *Record) Schema() *schema.Schema {
	sch, _ := schema.Parse(this)
	return sch
}

func (this *Record) IType(int32) int32 {
	return config.ITypeRecord
}

func (this *Record) Clone() any {
	r := *this
	return &r
}

func (this *Record) Upsert(u *updater.Updater, op *operator.Operator) bool {
	return true
}

func (this *Record) Getter(u *updater.Updater, coll *dataset.Collection, keys []string) error {
	uid := u.Uid()
	if uid == "" {
		return errors.New("Items.Getter uid not found")
	}
	var rows []*Record
	tx := db.Model(this).Where("uid = ?", uid)
	tx = tx.Omit("uid")
	if len(keys) > 0 {
		tx = tx.Where("_id IN ?", keys)
	}
	if tx = tx.Find(&rows); tx.Error != nil {
		return tx.Error
	} else {
		for _, v := range rows {
			coll.Receive(v.OID, v)
		}
	}
	return nil
}
func (this *Record) Setter(u *updater.Updater, bw dataset.BulkWrite) error {
	return bw.Submit()
}

func (this *Record) BulkWrite(u *updater.Updater) dataset.BulkWrite {
	return NewBulkWrite(this)
}
